package com.bitdf.txing.users.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.valid.SaveGroup;
import com.bitdf.txing.common.valid.UpdateGroup;
import com.bitdf.txing.users.entity.TeamInfoEntity;
import com.bitdf.txing.users.service.TeamInfoService;
import com.bitdf.txing.users.vo.TeamQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.stream.Collectors;



/**
 * 
 *
 * @author Lizhiwei
 * @email 123@qq.com
 * @date 2022-09-05 11:22:35
 */
@RestController
@Slf4j
@RequestMapping("${txing.request.path.users}/team")
public class TeamInfoController {
    @Autowired
    private TeamInfoService teamInfoService;

    /**
     * 分页查询
     */
    @RequestMapping("/list")
    public R list(@RequestBody TeamQueryVo queryVo){
        PageUtils page = teamInfoService.queryPage(queryVo);
        return R.ok().put("page", page);
    }


    /**
     * 根据id查询
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		TeamInfoEntity teamInfo = teamInfoService.getById(id);

        return R.ok().put("teamInfo", teamInfo);
    }

    /**
     *  创建团队
     */
    @SaCheckLogin
    @RequestMapping("/save")
    public R save(@Validated(SaveGroup.class) @RequestBody TeamInfoEntity teamInfo, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        teamInfo.setAttendCount(0);
        teamInfo.setFansCount(0);
        teamInfo.setLeaderId(StpUtil.getLoginIdAsLong());
		teamInfoService.save(teamInfo);
        log.info("团队：{} 创建成功", teamInfo.getTeamName());
        return R.ok();
    }

    /**
     * 修改团队信息(只有团队负责人可以修改)
     */
    @RequestMapping("/update")
    @SaCheckLogin
    public R update(@Validated(UpdateGroup.class) @RequestBody TeamInfoEntity teamInfo, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        if (StpUtil.getLoginIdAsLong() != teamInfo.getLeaderId()) {
            // 不是该团队负责人， 不得修改
            return R.error(TxCodeEnume.USER_NOT_PERM_EXCEPTION);
        }
        // 更新
		teamInfoService.updateById(teamInfo);
        return R.ok();
    }

    /**
     * 注销团队(只有团队负责人可以修改)
     */
    @RequestMapping("/delete/{id}")
    @SaCheckLogin
    public R delete(@PathVariable("id") Long id){
        boolean remove = teamInfoService.remove(new QueryWrapper<TeamInfoEntity>().lambda().eq(TeamInfoEntity::getId, id)
                .eq(TeamInfoEntity::getLeaderId, StpUtil.getLoginIdAsLong()));
        return remove ? R.ok() : R.error(TxCodeEnume.USER_NOT_PERM_EXCEPTION);
    }

}
